/**
 * Copyright &copy; 2017 <a href="https://gitee.com/hackempire/emsite-parent">emsite</a> All rights reserved.
 */
package com.empire.emsite.modules.cms.web.front;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.empire.emsite.common.web.BaseController;
import com.empire.emsite.modules.cms.utils.WiexinSignUtil;

/**
 * 类WeixinController.java的实现描述：测试Controller
 * 
 * @author arron 2017年10月30日 下午7:15:00
 */
@Controller
@RequestMapping(value = "${frontPath}/weixin")
public class WeixinController extends BaseController {

    /**
     * @param signature
     *            微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 随机数
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public String get(String signature, String timestamp, String nonce, String echostr, HttpServletRequest request) {

        System.out.println("=============================================== get start");
        for (Object o : request.getParameterMap().keySet()) {
            System.out.println(o + " = " + request.getParameter((String) o));
        }
        System.out.println("=============================================== get end");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
        if (WiexinSignUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }

        return "";
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public String post(String signature, String timestamp, String nonce, String echostr, HttpServletRequest request) {
        System.out.println("=============================================== post start");
        for (Object o : request.getParameterMap().keySet()) {
            System.out.println(o + " = " + request.getParameter((String) o));
        }
        System.out.println("=============================================== post end");
        StringBuilder result = new StringBuilder();
        result.append("<xml>" + "<ToUserName><![CDATA[toUser]]></ToUserName>"
                + "<FromUserName><![CDATA[fromUser]]></FromUserName>" + "<CreateTime>12345678</CreateTime>"
                + "<MsgType><![CDATA[text]]></MsgType>" + "<Content><![CDATA[你好]]></Content>" + "</xml>");
        return result.toString();
    }

}
